package com.atguigu.flink.chapter07;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/12/15 9:26
 */
public class Flink14_Timer_ProcessingTime {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        SingleOutputStreamOperator<String> mainStream = env
            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                String[] data = line.split(",");
                return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
            })
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
    
                private long timer;
    
                @Override
                public void onTimer(long timestamp,
                                    OnTimerContext ctx,
                                    Collector<String> out) throws Exception {
                    System.out.println("timestamp = " + timestamp);
                    out.collect("有传感器水位超过50, 发出黄色预警");
                }
                
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    // 注册定时器
                    // 水印超过50, 则5s之后发出预警信息
                    if (value.getVc() >= 50) {
                        timer = ctx.timerService().currentProcessingTime() + 5000;
                        System.out.println("timer = " + timer);
                        ctx.timerService().registerProcessingTimeTimer(timer);
                    }else if (value.getVc() < 20){
                        ctx.timerService().deleteProcessingTimeTimer(timer);
                    }
                }
            });
        
        mainStream.print("s1");
        
        env.execute();
    }
}
